./data folder.
sf::read_sf() function to load the data. Sampling is
straightforward: Apply the sf::st_sample to the loaded
shapefile, but make sure to apply the sf::st_as_sf()
function afterward to receive a full-fledged data table (with a geometry
column only).
library(dplyr)
cologne <- sf::read_sf("./data/cologne.shp")
cologne_50_points <-
cologne |>
sf::st_sample(50) |>
sf::st_as_sf()
immigrants_cologne.tif and
inhabitants_cologne.tif files in the ./data
folder.
library(terra)
immigrant_rates <-
terra::rast("./data/immigrants_cologne.tif") * 100 /
terra::rast("./data/inhabitants_cologne.tif")
immigrant_rates_at_point <- terra::extract(immigrant_rates, cologne_50_points)
immigrant_rates_at_point
## ID immigrants_cologne
## 1 1 NA
## 2 2 NA
## 3 3 NA
## 4 4 10.377358
## 5 5 NA
## 6 6 NA
## 7 7 NA
## 8 8 NA
## 9 9 NA
## 10 10 NA
## 11 11 NA
## 12 12 NA
## 13 13 NA
## 14 14 NA
## 15 15 NA
## 16 16 NA
## 17 17 NA
## 18 18 NA
## 19 19 NA
## 20 20 NA
## 21 21 NA
## 22 22 NA
## 23 23 NA
## 24 24 NA
## 25 25 NA
## 26 26 NA
## 27 27 NA
## 28 28 NA
## 29 29 NA
## 30 30 NA
## 31 31 NA
## 32 32 NA
## 33 33 3.529412
## 34 34 NA
## 35 35 NA
## 36 36 NA
## 37 37 NA
## 38 38 NA
## 39 39 NA
## 40 40 17.073171
## 41 41 NA
## 42 42 NA
## 43 43 NA
## 44 44 NA
## 45 45 NA
## 46 46 NA
## 47 47 NA
## 48 48 18.807339
## 49 49 NA
## 50 50 NA
# There are a lot of missing values.
sf::st_buffer() function. In that case, you should also set
a descriptive statistics function, e.g., with the option
fun = mean and its helpful companion option to consider
missing values na.rm = TRUE.
immigrant_rates_1000m_buffer <-
terra::extract(
immigrant_rates,
sf::st_buffer(cologne_50_points, 1000),
fun = mean,
na.rm = TRUE
)
immigrant_rates_1000m_buffer
## ID immigrants_cologne
## 1 1 18.258418
## 2 2 NaN
## 3 3 14.192946
## 4 4 13.767295
## 5 5 11.760282
## 6 6 27.234558
## 7 7 31.636059
## 8 8 13.165302
## 9 9 NaN
## 10 10 14.973438
## 11 11 13.162697
## 12 12 11.592882
## 13 13 14.022242
## 14 14 14.580221
## 15 15 9.827045
## 16 16 26.541320
## 17 17 48.611111
## 18 18 12.769264
## 19 19 17.705579
## 20 20 12.979616
## 21 21 13.104258
## 22 22 22.690476
## 23 23 23.877637
## 24 24 32.448624
## 25 25 12.902459
## 26 26 15.033232
## 27 27 26.306249
## 28 28 14.425409
## 29 29 17.251056
## 30 30 13.681955
## 31 31 15.557365
## 32 32 12.883983
## 33 33 14.546804
## 34 34 14.060584
## 35 35 14.040328
## 36 36 11.668190
## 37 37 13.897319
## 38 38 16.578273
## 39 39 13.719025
## 40 40 14.199787
## 41 41 17.995652
## 42 42 NaN
## 43 43 22.382594
## 44 44 19.555207
## 45 45 NaN
## 46 46 9.833143
## 47 47 27.358966
## 48 48 14.949831
## 49 49 12.528276
## 50 50 12.972539